package com.dqy.twserver.server.codec;

import com.dqy.twserver.server.dto.GameDto;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ReplayingDecoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

//解码器
public class DataDecode  extends ReplayingDecoder<Void> {
    static         GsonBuilder gsonBuilder=new GsonBuilder();
    static Logger logger = LoggerFactory.getLogger(DataDecode.class);
    @Override
    protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> list) throws Exception {
        logger.info("[DataDecode]开始解码...");
        int size = byteBuf.readInt();
        size= Integer.reverseBytes(size);
        logger.info("[DataDecode]读取到的字节长度.{}",size);
        byte[] resBytes=new byte[size];
        byteBuf.readBytes(resBytes);
        String json = new String(resBytes, "utf-8");
        logger.info("[DataDecode]解码得到的json:{}",json);
        GameDto gameDto = gsonBuilder.create().fromJson(json, GameDto.class);
        list.add(gameDto);

        logger.info("[DataDecode]解码完毕...");
    }
}
